#!/usr/bin/env ruby

# libraries
require 'rubygems'
require 'appscript'
require 'rexml/document'
require 'thread'
include Appscript

# application classes
require 'MALHandler'
require 'QTHandler'
require 'models'

# login information 
settings = {:user => 'youruser', :passwd => 'yourpassword', :video_refresh_time => 60}

# implementation

# starting connection with MAL
mal = MALHandler.new :user => settings[:user], :password => settings[:passwd]

# lets get informations about playing videos with Apple Script
qt = QTHandler.instance
qt_thread = Thread.new do
  loop do
    qt.refresh()
    video = qt.video
    if !video.nil? and video.ready_for_scrobble? and !video.scrobbled?
      puts "preparing to scrobble"
      anime_id = mal.get(:title => video.name)
      if !anime_id.nil?
        mal.set :anime_id => anime_id.to_s, :ep_val => video.episode.to_s
        puts "scrobbled episode " + video.episode.to_s + " of " + video.name.to_s
        video.scrobbled = true
      else
        puts "not found in your list"
      end
    end
    sleep(settings[:video_refresh_time])
  end
end

qt_thread.join